# -*- coding: utf-8 -*-

import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '90168591': {
        'API_KEY': 'jXeS4GEH8A58T3yCHsSJCx7XTFxAXPX7',
        'gateway': 'http://cashier.duoduopayment.com/payment/',
        'query_gateway': 'http://cashier.duoduopayment.com/query/',
    },
    '90168599': {
        'API_KEY': 'jmsemmfatf5PmZNyyDadHniZ7nd5ZYmd',
        'gateway': 'http://cashier.duoduopayment.com/payment/',
        'query_gateway': 'http://cashier.duoduopayment.com/query/',
    },
    '90168600': {
        'API_KEY': 'jHrtEsyGXHKnZnpSjJFdHmawMwrcRw8T',
        'gateway': 'http://cashier.duoduopayment.com/payment/',
        'query_gateway': 'http://cashier.duoduopayment.com/query/',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_md5_str(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(d, key):
    s = 'MerId={}&OrdId={}&OrdAmt={}&PayType=DT&CurCode=CNY&BankCode={}&' \
        'ProductInfo={}&Remark={}&ReturnURL={}&NotifyURL={}&SignType=MD5&MerKey={}'.format(
        d['MerId'], d['OrdId'], d['OrdAmt'], d['BankCode'],
        d['ProductInfo'], d['Remark'], d['ReturnURL'], d['NotifyURL'],
        key
    )
    return _gen_md5_str(s)


def generate_query_sign(d, key):
    s = '{}&{}&{}&{}'.format(
        d['MerId'], d['TimeStamp'], d['OrdId'], key
    )
    _LOGGER.info("duoduopay quegenerate_query_sign str: %s", s)
    return _gen_md5_str(s)


def generate_notify_sign(d, key):
    src = 'MerId={}&OrdId={}&OrdAmt={}&OrdNo={}&ResultCode={}&Remark={}&SignType={}'.format(
        d['MerId'], d['OrdId'], d['OrdAmt'], d['OrdNo'], d['ResultCode'], d['Remark'], d['SignType']
    )
    return _gen_md5_str(_gen_md5_str(src) + key)


# QUICKPAY	快捷支付
# WECHATQR	微信扫码
# WECHATWAP	微信 WAP
# ALIPAYQR	支付宝扫码
# ALIPAYWAP	支付宝 WAP
# QQWALLET	QQ钱包扫码
# QQWAP	QQ WAP
# JDWALLET	京东钱包
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WECHATWAP'
    elif service == 'alipay':
        payType = 'ALIPAYWAP'
    elif service == 'qq':
        payType = 'QQWAP'
    elif service == 'jd':
        payType = 'JDWALLET'
    else:
        payType = 'QUICKPAY'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    api_key = _get_api_key(mch_id)
    service = info.get('service')
    parameter_dict = {
        'MerId': mch_id,
        'OrdId': str(pay.id),
        'OrdAmt': '%.2f' % pay_amount,
        'PayType': 'DT',
        'CurCode': 'CNY',
        'BankCode': _get_pay_type(service),
        'ProductInfo': 'charge',
        'Remark': 'charge',
        'ReturnURL': '{}/pay/api/{}/duoduopay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'NotifyURL': '{}/pay/api/{}/duoduopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'SignType': 'MD5',
    }
    parameter_dict['SignInfo'] = generate_sign(parameter_dict, api_key)
    html_text = _build_form(parameter_dict, _get_gateway(mch_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info("duoduopay create data : %s, %s", parameter_dict, url)
    return {'charge_info': url}


def verify_notify_sign(params, key):
    sign = params['SignInfo']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("duoduopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# success|9999
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("duoduopay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['OrdId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('duoduopay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay or pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = str(data['ResultCode'])
    mch_id = pay.mch_id
    trade_no = data['OrdNo']
    total_fee = float(data['OrdAmt'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # 20—支付成功， 其它为未知
    if trade_status == 'success002':
        _LOGGER.info('duoduopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('Version', '2.1'),
        ('SignType', 'MD5'),
        ('Charset', 'UTF-8'),
        ('TimeStamp', local_now().strftime('%Y%m%d%H%M%S')),
        ('MerId', app_id),
        ('OrdId', str(pay_order.id)),

    ))
    parameter_dict['SignInfo'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("duoduopay query data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("duoduopay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['tradeStatus'])
        trade_no = data['sysOrdId']
        total_fee = float(data['merOrdAmt'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 000：初始提交
        # 001：进行中
        # 002：付款成功
        # 003：付款失败
        # 004：付款退款
        if trade_status == '002':
            _LOGGER.info('duoduopay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('duoduopay data error, status_code: %s', response.status_code)
